// 引入接口地址
import { userList, userCount } from '../../../request/api'
// 定义接口
interface userState {
  userList: Array<Object>
  total: number
  size: number
  page: number
}
// 菜单仓库模块
const state = {
  userList: [],
  total: 0,
  size: 3,
  page: 1
}

const mutations = {
  REQ_USERLIST (state: userState, payload: any) {
    return (state.userList = payload)
  },
  REQ_COUNT (state: userState, payload: any) {
    return (state.total = payload)
  },
  CHANGE_PAGE (state: userState, payload: any) {
    return (state.page = payload)
  }
}

const actions = {
  userList_Action (context: any) {
    // 调用用户列表接口
    userList({
      size: context.state.size,
      page: context.state.page
    }).then((res: any) => {
      console.log(res)
      if (res.data.code == 200) {
        let list = res.data.list || []
        // 判断除第一页外当前页是否还有管理员数据
        if (context.state.page != 1 && list.length == 0) {
          // 调用改变页数行动
          context.dispatch('changePage_Action', context.state.page - 1)
        }
        context.commit('REQ_USERLIST', res.data.list)
      }
    })
  },
  userCount_Action ({ commit }: any) {
    // 调用管理员总数接口
    userCount().then((res: any) => {
      console.log(res)
      if (res.data.code == 200) {
        commit('REQ_COUNT', res.data.list[0].total)
      }
    })
  },
  changePage_Action (context: any, payload: any) {
    // 点击切换选中页面
    context.commit('CHANGE_PAGE', payload)
    // 调用渲染管理员列表行动
    context.dispatch('userList_Action')
  }
}

const getters = {
  // 获取管理员列表
  getUserList (state: userState) {
    return state.userList
  },
  // 获取管理员总数
  getTotal (state: userState) {
    return state.total
  },
  // 获取页数展示条数
  getSize (state: userState) {
    return state.size
  }
}

// 导出菜单仓库
export default {
  state,
  mutations,
  actions,
  getters,
  namespaced: true
}
